﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace YuFeng.Web.Helpers
{
    public class SecurityHelper
    {
        public static string MD5Encrypt(string cleanText)
        {
            byte[] result = Encoding.Default.GetBytes(cleanText);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "");
        }

        public static string DESEncrypt(string cleanText, string key, string iv)
        {
            byte[] btKey = Encoding.UTF8.GetBytes(MD5Encrypt(key).Substring(0, 8));
            byte[] btIV = Encoding.UTF8.GetBytes(MD5Encrypt(iv).Substring(0, 8));

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] inData = Encoding.UTF8.GetBytes(cleanText);
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
                {
                    cs.Write(inData, 0, inData.Length);

                    cs.FlushFinalBlock();
                }
                return Convert.ToBase64String(ms.ToArray());
            }
        }

        public static string DESDecrypt(string encryptedString, string key, string iv)
        {
            byte[] btKey = Encoding.UTF8.GetBytes(MD5Encrypt(key).Substring(0, 8));
            byte[] btIV = Encoding.UTF8.GetBytes(MD5Encrypt(iv).Substring(0, 8));

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] inData = Convert.FromBase64String(encryptedString);
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                {
                    cs.Write(inData, 0, inData.Length);
                    cs.FlushFinalBlock();
                }
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }
}